import {defineStore} from "pinia";
import {ref} from "vue";
import {loginAPI, sendCodeAPI} from "@/api/userApi.ts";
import {loginInterface, userInterface} from "@/components/Loign/interface/interface.ts";
import {getUserInfo, removeUserInfo, setUserInfo} from "@/utils/localStorage.ts";


const useUserStore = defineStore('userStore', () => {
    const loginDialog = ref<boolean>(false)
    const flag = ref<boolean>(true)
    const userInfo = ref<userInterface>(getUserInfo() || {})
    const changeDialog = (flag: boolean): void => {
        loginDialog.value = flag
    }
    const changeFlag = (value: boolean): void => {
        flag.value = value
    }
    const getCode = async (phone: string): Promise<string> => {
        const {data} = await sendCodeAPI(phone)
        return data
    }
    const login = async (formData: loginInterface): Promise<userInterface> => {
        const {data}: userInterface = await loginAPI(formData)
        userInfo.value = data
        setUserInfo(data)
        return data
    }
    const logout = (): void => {
        userInfo.value = {}
        removeUserInfo()
    }

    return {
        loginDialog,
        flag,
        userInfo,
        changeDialog,
        changeFlag,
        getCode,
        login,
        logout,
    }
})

export default useUserStore
